package gee

import (
	"strings"
)

type Node struct {
	Pattern  string  `json:"pattern"`  //待匹配的路由 eg: /p/:lang
	Part     string  `json:"part"`     // 路由中的一部分 eg :lang
	Children []*Node `json:"children"` //子节点
	IsWild   bool    `json:"is_wild"`  //是否精准匹配 part中含有：或 * 为ture
}

func (n *Node) matchChild(part string) *Node {
	for _, child := range n.Children {
		if child.Part == part || child.IsWild {
			return child
		}
	}
	return nil
}

func (n *Node) matchChildren(part string) []*Node {
	nodes := make([]*Node, 0)
	for _, child := range n.Children {
		if child.Part == part || child.IsWild {
			nodes = append(nodes, child)
		}
	}
	return nodes
}

//pattern ="/p/log/index" parts = ["p","log","index"], height = 0
func (n *Node) insert(pattern string, parts []string, height int) {
	if len(parts) == height {
		n.Pattern = pattern
		return
	}
	part := parts[height]
	child := n.matchChild(part)
	if child == nil {
		child = &Node{
			Part:   part,
			IsWild: part[0] == ':' || part[0] == '*',
		}
		n.Children = append(n.Children, child)
	}
	child.insert(pattern, parts, height+1)
}

func (n *Node) search(parts []string, height int) *Node {
	if len(parts) == height || strings.HasPrefix(n.Part, "*") {
		if n.Pattern == "" {
			return nil
		}
		return n
	}

	part := parts[height]
	children := n.matchChildren(part)
	for _, child := range children {
		result := child.search(parts, height+1)
		if result != nil {
			return result
		}
	}
	return nil
}
